package cn.dmp.tools;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

//java版计算signature签名
public class BaiduLBS {

    private static final String LBSURL = "http://api.map.baidu.com/geocoder/v2/?";

    public static String businessInfo(String lat, String longitude) {


        String business = null;

        try {
            Thread.sleep(50);

            Map paramsMap = new LinkedHashMap<String, String>();
            paramsMap.put("callback", "renderReverse");
            paramsMap.put("location", lat+","+longitude);
            paramsMap.put("output", "json");
            paramsMap.put("pois", "1"); // 当前坐标点附近一公里范围内的数据信息
            paramsMap.put("ak", "TuNTBLFWhrnbmvSCaphTAx4RDG74u8gj");

            String paramsStr = toQueryString(paramsMap);

            String wholeStr = new String("/geocoder/v2/?" + paramsStr + "OX1P5cyk6ddohvuLRmeBnDGGuWuTvA6O");

            // 对上面wholeStr再作utf8编码
            String tempStr = URLEncoder.encode(wholeStr, "UTF-8");

            // 调用下面的MD5方法得到最后的sn签名7de5a22212ffaa9e326444c75a58f9a0
            String sn = MD5(tempStr);


            // 请求百度的服务器 -> json -> httpclient
            HttpClient httpClient = new HttpClient();
            GetMethod getMethod = new GetMethod(LBSURL + paramsStr + "&sn=" + sn);
            int code = httpClient.executeMethod(getMethod);
            if (code == 200) {
                String response = getMethod.getResponseBodyAsString(); // 获取本期请求服务器响应回来的内容
                getMethod.releaseConnection(); // 释放本次请求

                String delHead = response.replace("renderReverse&&renderReverse(", "");
                String jsonStr = delHead;
                if (response.startsWith("renderReverse&&renderReverse(")) {
                    jsonStr = delHead.substring(0, delHead.length() - 1);
                }


                System.out.println("jsonStr = " + jsonStr);
                // 解析json字符串中的business节点数据
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                System.out.println("jsonObject = " + jsonObject);


                int status = jsonObject.getIntValue("status");
                if (status == 0) {
                    JSONObject resultObject = jsonObject.getJSONObject("result");
                    business = resultObject.getString("business");

                    if (StringUtils.isEmpty(business)) { // 如果business是空的，则继续往下解析，解析pois中的第一个对象中的tag节点数据
                        JSONArray jsonArray = resultObject.getJSONArray("pois");
                        if (jsonArray.size() > 0) {
                            business = jsonArray.getJSONObject(0).getString("tag");
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            // return null;
        }
        return business;
    }

    // 对Map内所有value作utf8编码，拼接返回结果
    public static String toQueryString(Map<?, ?> data)
            throws UnsupportedEncodingException {
        StringBuffer queryString = new StringBuffer();
        for (Entry<?, ?> pair : data.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }
        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }
        return queryString.toString();
    }

    // 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
    public static String MD5(String md5) {
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            byte[] array = md.digest(md5.getBytes());
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < array.length; ++i) {
                sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100)
                        .substring(1, 3));
            }
            return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
        }
        return null;
    }
}